package com.aoip.telemetry.telemetry.receive.message.common;

import com.aoip.telemetry.telemetry.core.redis.RedisCache;
import com.aoip.telemetry.telemetry.entity.enums.AbnoTypeEnum;
import com.aoip.telemetry.telemetry.entity.enums.CacheKeyEnum;
import com.aoip.telemetry.telemetry.mq.rabbitmq.SendMsgToRabbitMq;
import com.aoip.telemetry.telemetry.receive.util.ConfirmUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;


/**
 * 原始报文数据发送到消息中间件，给解析端解析数据
 *
 * @author chenbai
 * @version 1.0
 * @date 2021/6/17 9:11
 */
@ChannelHandler.Sharable
@Slf4j
@Component
public class MessageSendMqHandler extends ChannelInboundHandlerAdapter {

    private static MessageSendMqHandler messageSendMqHandler;
    private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private String protocolId;
    @Resource
    private SendMsgToRabbitMq sendMsgToMq;
    @Resource
    private RedisCache redisCache;
    public MessageSendMqHandler() {
    }

    public MessageSendMqHandler(String protocolId) {
        this.protocolId = protocolId;
    }

    @PostConstruct
    public void init() {
        messageSendMqHandler = this;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ctx.fireChannelRead(msg);
        log.error("TCP接收报文：{}", msg);
        String originalMessage = msg.toString();
        originalMessage = originalMessage.trim();
        String stCode = getStCode(originalMessage);
//        if (!StringUtils.hasText(stCode)) {
//            return;
//        }
//        if(unregisteredStCode(stCode)) {
//            return;
//        }
        messageSendMqHandler.redisCache.deleteObject(CacheKeyEnum.ST_GP_ABNO_INFO + ":" + AbnoTypeEnum.LAST_HEARTBEAT + ":" + stCode);
        messageSendMqHandler.redisCache.setCacheObject(CacheKeyEnum.ST_GP_ABNO_INFO + ":" + AbnoTypeEnum.LAST_HEARTBEAT + ":" + stCode, LocalDateTime.now().format(dtf));

        String confirm = ConfirmUtil.generateConfirm(originalMessage);
        if (StringUtils.hasText(confirm)) {
            Channel channel = ctx.channel();
            ByteBuf heapBuffer = channel.alloc().heapBuffer();
            heapBuffer.writeBytes(confirm.getBytes());
            ctx.writeAndFlush(heapBuffer);
        }
        messageSendMqHandler.sendMsgToMq.sendMsg("exchange_telemetry_msg", "router_key_telemetry_hydrology", originalMessage);
    }

    private String getStCode(String originalMessage) {
        int st = originalMessage.indexOf("ST");
        int stCodeBeginIndex = st + 3;
        int stCodeEndIndex = originalMessage.indexOf(" " , 3);
        return originalMessage.substring(stCodeBeginIndex, stCodeEndIndex);
    }


    /**
     * 未注册的测站，不存在，返回true，存在返回false
     * @author chenbai
     * @date 2022/11/25
     * @param stCode 测站编码
     * @return java.lang.Boolean
     **/
    private boolean unregisteredStCode(String stCode){
        Collection<String> keys = messageSendMqHandler.redisCache.keys(CacheKeyEnum.STATION + ":*" + stCode);
        return keys == null || keys.size() < 1;
    }
}
